package com.delivery.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.delivery.constant.MessageConstant;
import com.delivery.context.BaseContext;
import com.delivery.dto.OrderPaymentDTO;
import com.delivery.dto.PlaceOrderDTO;
import com.delivery.entity.AddressBook;
import com.delivery.entity.OrderDetail;
import com.delivery.entity.Orders;
import com.delivery.entity.User;
import com.delivery.exception.BaseException;
import com.delivery.exception.OrderBusinessException;
import com.delivery.mapper.*;
import com.delivery.service.OrderService;
import com.delivery.utils.WeChatPayUtil;
import com.delivery.vo.OrderPaymentVO;
import com.delivery.vo.PlaceOrderVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;


    /**
     * 用户下单
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public PlaceOrderVO placeOrder(PlaceOrderDTO dto) {

        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        orders.setUserId(BaseContext.getCurrentId());
        // 拿到当前时间戳作为订单编号
        orders.setNumber( System.currentTimeMillis() + "");
        orders.setStatus(Orders.PENDING_PAYMENT); // 待支付
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UNPAID);

        // 需要补充地址信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        orders.setAddress(addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());

        // 补充用户信息
        User user =  userMapper.selectById(orders.getUserId());
        orders.setUserName(user.getName());

        //  插入订单数据
        ordersMapper.insert(orders);

        // 把购物车里面的菜品和套餐都添加到订单详情中 order_detail表
        // 先看看购物车里面怎么个事
        List<OrderDetail> orderDetails = new ArrayList<>();
        shoppingCartMapper.selectByUserId(BaseContext.getCurrentId())
                .forEach(cart -> {
                    OrderDetail orderDetail = new OrderDetail();
                    BeanUtils.copyProperties(cart, orderDetail, "id");
                    orderDetail.setOrderId(orders.getId());
                    orderDetails.add(orderDetail);
                });
        if(orderDetails.size() > 0){
            orderDetailMapper.insertBatch(orderDetails);
            // 处理完订单详情后，清空购物车
            shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        }else{
            // 购物车为空
            throw new BaseException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        return PlaceOrderVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrderPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.PENDING_CONFIRMATION)
                .payStatus(Orders.PAID)
                .checkOutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }

}
